package com.imooc.maokeyang.alllearning.config;

import com.imooc.maokeyang.alllearning.util.BeanUtils;
import com.imooc.maokeyang.alllearning.util.JsonUtils;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;

@Configuration
@EnableCaching
public class CacheConfig {

    private final static int NO_PARAM_KEY = 0;

    private final static String SP = ":";

    @Bean
    public KeyGenerator keyGenerator() {
        return (Object target, Method method, Object... params) -> {

            StringBuilder sb = new StringBuilder();

            // 类名
            sb.append(target.getClass().getName()).append(SP);

            // 方法名
            sb.append(method.getName()).append(SP);

            // 参数
            if (params.length > 0) {
                for (Object object: params) {
                    if (BeanUtils.isSimpleValueType(object.getClass())) {
                        sb.append(object);
                    } else {
                        sb.append(JsonUtils.toJson(object));
                    }
                }
            } else {
                sb.append(NO_PARAM_KEY);
            }

            return sb.toString();
        };
    }

}
